package com.cj.myblog.common.util;

import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

/**
 * Created by Administrator on 2017-09-14.
 */
public class PageUtil {

    /**
     * 创建分页请求。
     *
     * @param start 每页开始条数
     * @param length 每页条数
     * @param sortType 排序字段
     * @param direction 排序方向
     */
    public static PageRequest buildPageRequest(int start, int length, String sortType, String direction) {
        //当前页
        int pageNum = start/length +1 ;
        //每页条数
        int pageSize = length;

        Sort sort = null;
        if (!StrUtil.isNotBlank(sortType)) {
            return new PageRequest(pageNum - 1, pageSize);
        } else if (StrUtil.isNotBlank(direction)) {
            if (Sort.Direction.ASC.equals(direction)) {
                sort = new Sort(Sort.Direction.ASC, sortType);
            } else {
                sort = new Sort(Sort.Direction.DESC, sortType);
            }
            return new PageRequest(pageNum - 1, pageSize, sort);
        } else {
            sort = new Sort(Sort.Direction.DESC, sortType);
            return new PageRequest(pageNum - 1, pageSize, sort);
        }
    }

    public static PageRequest buildPageRequest(int start, int length,  String sortType) {
        return buildPageRequest(start, length, sortType, null);
    }

    public static PageRequest buildPageRequest(int start, int length,  Sort sort) {
        return new PageRequest(start, length, sort);
    }

    public static PageRequest buildPageRequest(int start, int length) {
        return buildPageRequest(start, length, null, null);
    }



}
